//
//  SelectLocationView.m
//  MeterMart
//
//  Created by ENERGY on 2018/9/25.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "SelectLocationView.h"

@interface SelectLocationView()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic,strong)UIScrollView * scrollView;//滑动视图
@property(nonatomic,strong)NSMutableArray * areaMuArray;//拼接地址使用的数组,存的都是每一级的字典
@property(nonatomic,strong)NSDictionary * itemDic;//创建一个初始化的字典
@property(nonatomic,strong)NSMutableArray * provinceArray;
@property(nonatomic,strong)NSMutableArray * cityArray;
@property(nonatomic,strong)NSMutableArray * areaArray;
@property (nonatomic, strong)UIView * whiteView;
@property (nonatomic, strong)NSString * provinceStr;//省
@property (nonatomic, strong)NSString * cityStr;//城市
@property (nonatomic, strong)NSString * areaStr;//区
@property (nonatomic, strong)UIButton * provinceBtn;
@property (nonatomic, strong)UIButton * cityBtn;
@property (nonatomic, strong)UIButton * areaBtn;
- (void)closeBtnClick:(int)currenN;
@end
//控制器上的地址
//http://www.healthmanage.cn/android/android/healthMallAndroidAction_getAddrByLevel.action
@implementation SelectLocationView(networking)
#pragma mark - 市县区数据请求
- (void)cityListHttpRequestIdStr:(NSString *)parentIdStr cityArray:(NSMutableArray *)acityArray buttonTag:(int)btnTag tableViewTag:(int)aTag{
    NSDictionary *paramsDic = @{@"addressid":parentIdStr};
    AFHTTPSessionManager *messageManager = [AFHTTPSessionManager manager];
    messageManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [messageManager POST:@"http://yimi.sencant.com/index.php/usiosApi/addressChoices" parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        __weak typeof (self)weakSelf = self;
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        NSLog(@"输出市县区数据列表。。。。%@",resultDic);
        if ([resultDic[@"sign"] isEqualToString:@"1"]){
            NSArray *itemArray = [[resultDic[@"list"][@"address"] reverseObjectEnumerator] allObjects];
            for (NSDictionary *dic in itemArray){
                [acityArray addObject:dic];
            }
            UIButton *button = (UIButton *)[self viewWithTag:btnTag+1];
            [button setTitle:@"请选择" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            
            weakSelf.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH*aTag, SCREEN_HEIGHT-SCREEN_HEIGHT/3-75);
            UITableView *tableV = (UITableView *)[weakSelf.whiteView viewWithTag:aTag];
            [tableV reloadData];
            weakSelf.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH*(aTag-1), 0);
        }else{
            if (aTag == 3){
                //判断如果是第三个就没有数据了，那么后面一个都替换
                [weakSelf.areaMuArray replaceObjectAtIndex:aTag-1 withObject:self.itemDic];
            }
            //后面无数据界面弹下，显示地址
            [self closeBtnClick:1];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)getAreaListData{
    
}
@end
@implementation SelectLocationView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
//        self.itemDic = @{@"adCode":@"",@"adName":@"",@"id":@"",@"parentId":@""};
        self.itemDic = @{@"addressid":@"",@"area_name":@"",@"area_parent_id":@""};
        self.areaMuArray = [NSMutableArray arrayWithObjects:_itemDic,_itemDic,_itemDic, nil];
        self.cityArray = [NSMutableArray new];
        self.areaArray = [NSMutableArray new];
        self.alpha = 0;
        UIButton * bgBtn = [[UIButton alloc] initWithFrame:frame];
        bgBtn.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.75];
        [bgBtn addTarget:self action:@selector(cancelView) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:bgBtn];
        //白色背景
        UIView * whiteView = [[UIView alloc] init];
        whiteView.backgroundColor = [UIColor whiteColor];
        self.whiteView = whiteView;
        [self addSubview:whiteView];
        whiteView.frame = CGRectMake(0, bgBtn.centerY - 80/WIDTH_6_SCALE, SCREEN_WIDTH, bgBtn.height/2 + 80/WIDTH_6_SCALE);
        //标题
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = @"选择地区";
        titleLabel.textColor = [UIColor darkGrayColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont systemFontOfSize:15];
        [whiteView addSubview:titleLabel];
        titleLabel.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40/WIDTH_6_SCALE);
        //关闭按钮
        UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [closeBtn setBackgroundColor:[UIColor orangeColor]];
        [closeBtn setImage:[UIImage imageNamed:@"cross"] forState:UIControlStateNormal];
        [whiteView addSubview:closeBtn];
        closeBtn.frame = CGRectMake(SCREEN_WIDTH - 40/WIDTH_6_SCALE, titleLabel.top + 5/WIDTH_6_SCALE, 30/WIDTH_6_SCALE, 30/WIDTH_6_SCALE);
        [closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        //省市区按钮
        for (int i = 0; i < 3; i ++){
            UIButton *sBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            if (i == 0){
                [sBtn setTitle:@"请选择" forState:UIControlStateNormal];
            }
            sBtn.titleLabel.font = [UIFont systemFontOfSize:13];
            sBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
            [sBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            sBtn.tag = i+10;
            [sBtn addTarget:self action:@selector(selectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [whiteView addSubview:sBtn];
            sBtn.frame = CGRectMake(20/WIDTH_6_SCALE + (70*i)/WIDTH_6_SCALE, titleLabel.bottom + 5/WIDTH_6_SCALE, 70/WIDTH_6_SCALE, 29/WIDTH_6_SCALE);
        }
        self.provinceBtn = (UIButton *)[whiteView viewWithTag:10];
        self.cityBtn = (UIButton *)[whiteView viewWithTag:11];
        self.areaBtn = (UIButton *)[whiteView viewWithTag:12];
        //分割
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = getColor(textGrayColor);
        [whiteView addSubview:lineView];
        lineView.frame = CGRectMake(0, 74/WIDTH_6_SCALE, SCREEN_WIDTH, 1/WIDTH_6_SCALE);
        //
        self.scrollView = [[UIScrollView alloc] init];
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.pagingEnabled = YES;
        [whiteView addSubview:self.scrollView];
        self.scrollView.backgroundColor = [UIColor cyanColor];
        self.scrollView.frame = CGRectMake(0, lineView.bottom, SCREEN_WIDTH, whiteView.height - 75/WIDTH_6_SCALE);
        for (int i = 0; i < 3; i ++)
        {
            UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
            tableView.delegate = self;
            tableView.dataSource = self;
            tableView.rowHeight = 30/WIDTH_6_SCALE;
            tableView.tag = i+1;
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            [self.scrollView addSubview:tableView];
            tableView.frame = CGRectMake(SCREEN_WIDTH * i, 0, SCREEN_WIDTH, self.scrollView.height);
        }
    }return self;
}
- (void)getLocationListArray:(NSArray *)dataArray{
    self.provinceArray = [NSMutableArray arrayWithArray:dataArray];
    UITableView * proVinceTableView = (UITableView *)[self.whiteView viewWithTag:1];
    [proVinceTableView reloadData];
    UITableView * cityTableView = (UITableView *)[self.whiteView viewWithTag:2];
    [cityTableView reloadData];
    UITableView * areaTableView = (UITableView *)[self.whiteView viewWithTag:3];
    [areaTableView reloadData];
}
#pragma mark - action
- (void)showView{
    [[UIApplication sharedApplication].delegate.window addSubview:self];
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 1;
    }];
}
- (void)cancelView{
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 0 ;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
#pragma mark --- 选择标头按钮
- (void)selectBtnClick:(UIButton *)btn{
    if (btn.tag == 10){
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }else if (btn.tag == 11){
        if (self.scrollView.contentSize.width>=2*SCREEN_WIDTH){
            self.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
        }
    }else{
        if (self.scrollView.contentSize.width>=3*SCREEN_WIDTH){
            self.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH*2, 0);
        }
    }
}
#pragma mark --- UITableViewDelegate和DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 1){
        return self.provinceArray.count;
    }else if(tableView.tag == 2){
        return self.cityArray.count;
    }else{
        return self.areaArray.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }if (tableView.tag == 1){
        NSDictionary *dic  = [NSDictionary dictionaryWithDictionary:self.provinceArray[indexPath.row]];
        cell.textLabel.text = dic[@"area_name"];
    }else if(tableView.tag == 2)
    {
        NSDictionary *dic  = [NSDictionary dictionaryWithDictionary:self.cityArray[indexPath.row]];
        cell.textLabel.text = dic[@"area_name"];
    }else{
        NSDictionary *dic  = [NSDictionary dictionaryWithDictionary:self.areaArray[indexPath.row]];
        cell.textLabel.text = dic[@"area_name"];
    }
    cell.textLabel.font = [UIFont systemFontOfSize:13];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 1){
        //第二次选择的时候
        [self.cityArray removeAllObjects];
        [self showSelectViewArray1:self.provinceArray indexPathRow:(int)indexPath.row buttonTag1:10 xPoint:2 cityArray:_cityArray];
        //第二次切换地区时，后面的按钮取消不显示
        [self.areaBtn setTitle:@"" forState:UIControlStateNormal];
        [self.areaBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }else if(tableView.tag == 2){
        [self.areaArray removeAllObjects];
        [self showSelectViewArray1:self.cityArray indexPathRow:(int)indexPath.row buttonTag1:11 xPoint:3 cityArray:self.areaArray];
    }else{
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:_areaArray[indexPath.row]];
        [_areaMuArray replaceObjectAtIndex:2 withObject:dic];
        
        [self.areaBtn setTitle:dic[@"area_name"] forState:UIControlStateNormal];
        [self.areaBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        if (self.getDetailAddressBlock) {
            self.getDetailAddressBlock(self.provinceBtn.titleLabel.text, self.cityBtn.titleLabel.text, self.areaBtn.titleLabel.text);
        }
        [self closeBtnClick:1];
    }
}
#pragma mark --- 选中后执行方法
//参数说明：1：上一个表格数组，2：点击的是第几行数据，3：标题按钮的tag值，4：滑动视图有几个SCREEN_WIDTH，5：下一个表格数组
-(void)showSelectViewArray1:(NSMutableArray *)aprovinceArray indexPathRow:(int)aRow buttonTag1:(int)aTag1 xPoint:(int)aXi cityArray:(NSMutableArray *)acityArray{
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:aprovinceArray[aRow]];
    UIButton *buttonN1 = (UIButton *)[self viewWithTag:aTag1];
    [buttonN1 setTitle:dic[@"area_name"] forState:UIControlStateNormal];
    [buttonN1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [self.areaMuArray replaceObjectAtIndex:aXi-2 withObject:dic];
    if (aXi == 2) {
        [self cityListHttpRequestIdStr:dic[@"addressid"] cityArray:acityArray buttonTag:aTag1 tableViewTag:aXi];
    }else{
        [self cityListHttpRequestIdStr:dic[@"addressid"] cityArray:acityArray buttonTag:aTag1 tableViewTag:aXi];
    }
}

#pragma mark --- 关闭按钮
- (void)closeBtnClick:(int)currenN{
    [self cancelView];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self closeBtnClick:0];
}

@end
